import {ModalForm, ProFormSelect, ProFormText, ProFormTreeSelect, ProFormDependency, DrawerForm, ProFormRadio } from "@ant-design/pro-components";
import IHttp, {IAxiosResponse} from "@/services/http.service";
import React, {useEffect, useState} from "react";
import {Form, message, Drawer, Button, Input, Space, Card, Tag, Radio} from "antd";
import { MinusCircleOutlined, PlusOutlined } from '@ant-design/icons';
import { firstValueFrom } from "rxjs"
import environment from "@/environment";
import IHelper from "@/services/helper.service";
import { divide } from "lodash";
import { useForm } from "antd/es/form/Form";

type CreateFormProps = {
  title?: string
  desc?: string
  bili_type?: string
  ks_type?: string
  common_tag?: string[]
  dy_tag?: string[]
  account?: string[]
  video_type?: number
  video_bili_bvid?: string
  video_upload_id?: string
}

type IProps = {
  item: API.PubTaskItem | undefined
  onCancel: () => void
  onRefreshTable: () => void
}

export default function BatchAddForm({item, onCancel, onRefreshTable}: IProps) {
  const open = Boolean(item)
  const [form] = useForm()
  useEffect(() => {
    form.resetFields()
  }, [open])
  async function onFinish(values: any) {
    console.log("onFinish", values)
    let items = []
    if (values.type === 2) {
      try {
        items = JSON.parse(values.json).reverse()
      } catch(e) {}
    }
    if (values.type === 1) {
      items = values.items
    }
    if (!Array.isArray(items) || items.length <= 0) {
      message.error("至少需要1个item")
      return 
    }
    const res = await firstValueFrom(IHttp.createMultiplePubTask(item?.id as number, {items}))
    if (!res.status) return
    onRefreshTable()
  }
  return (
    <Drawer
      width={360}
      open={open}
      title={"批量添加"}
      destroyOnClose
      onClose={onCancel}
      maskClosable={false}
      footer={(
        <div className="text-right">
          <Space>
            <Button onClick={onCancel}>
              取消
            </Button>
            <Button type="primary" onClick={() => form.submit()}>
              确定
            </Button>
          </Space>
        </div>
        
      )}
    >
      <Form
        name="dynamic_form_nest_item"
        onFinish={onFinish}
        form={form}
        style={{ maxWidth: 600 }}
        autoComplete="off"
        initialValues={{type: 1}}
        // layout="vertical"
      >
        <Form.Item name="type" label="添加方式" >
          <Radio.Group>
            <Radio value={1}>手动</Radio>
            <Radio value={2}>json</Radio>
          </Radio.Group>
        </Form.Item>
        <Form.Item 
          dependencies={["type"]}
          noStyle
        >
          {({ getFieldValue }) => {
            const type = getFieldValue("type")
            if (type === 1) {
              return (
                <Form.List name="items">
                  {(fields, { add, remove }) => (
                    <>
                      {fields.map(({ key, name, ...restField }, idx) => (
                        <Card 
                          size="small"
                          className="my-2" 
                          key={key} 
                          title={<Tag color="magenta">{idx + 1}</Tag>}
                          // title={`第${idx + 1}个`}
                          extra={<MinusCircleOutlined onClick={() => remove(name)} />}
                        >
                          <Form.Item
                            {...restField}
                            name={[name, 'title']}
                            rules={[{ required: true, message: 'Missing title' }]}
                          >
                            <Input placeholder="标题" />
                          </Form.Item>
                          <Form.Item
                            {...restField}
                            name={[name, 'video_bili_bvid']}
                            rules={[{ required: true, message: 'Missing bvid' }]}
                          >
                            <Input placeholder="bvid" />
                          </Form.Item>
                        </Card>
                        // <Space key={key} style={{ display: 'flex', marginBottom: 8 }} align="baseline">
                          
                        //   <MinusCircleOutlined onClick={() => remove(name)} />
                        // </Space>
                      ))}
                      <Form.Item>
                        <Button type="dashed" onClick={() => add()} block icon={<PlusOutlined />}>
                          Add field
                        </Button>
                      </Form.Item>
                    </>
                  )}
                </Form.List>
              )
            }
            if (type === 2) {
              return (
                <Form.Item initialValue={JSON.stringify([{title: "标题", video_bili_bvid: "bvid"}])} name={"json"} label="json" labelCol={{span: 24}} tooltip={`格式如[{title: "标题", video_bili_bvid: "bvid"}]`}>
                  <Input.TextArea rows={4} placeholder="输入json" />
                </Form.Item>
              )
            }
          }}
        </Form.Item>
        {/* <ProFormDependency name={["type"]}>
          {({type}) => {
            
          }}
        </ProFormDependency> */}
        
      </Form>
    </Drawer>
  )
}
